package com.woniu108.valueAdded.consumer;


import com.woniu108.valueAdded.model.UserVip;
import com.woniu108.valueAdded.service.UserVipService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;

@Component
@RabbitListener(queues = "check_vip_queue")
public class CheckUserVipTimeConsumer {

    @Resource
    private UserVipService userVipService;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @RabbitHandler
    public void checkUserVipTime(String userId) {
        //获取用户vip信息
        UserVip userVip = userVipService.getById(userId);
        LocalDateTime vipEndTime = userVip.getVipEndTime();
        LocalDateTime vipStartTime = userVip.getVipStartTime();
        if(vipEndTime.isAfter(LocalDateTime.now())){
            //若未过期，则获取获取vip使用时间
            if(Duration.between(vipStartTime,LocalDateTime.now()).toDays()%30==0){
                //当开始时间与当前时间相隔为30的倍数时,发放免费洗车次数,次数重置到两次,
                // 否则未到vip新周期,不补充vip免费次数
                userVip.setFreeNum(2);
                userVipService.updateById(userVip);
            }
            //vip未过期,将检测消息重新发送到延迟队列,下个天数继续监测
            rabbitTemplate.convertAndSend("check_vip_time_queue",userId);
        }
        //若已过期,则不再重新加入延迟队列检测vip天数信息
    }


}
